package com.qf.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "CookieServlet",urlPatterns = "cookie")
public class CookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //服务器端生成cookie步骤
        createCookie(request, response, "uname", "tom", 20000);


    }

    private void createCookie(HttpServletRequest request, HttpServletResponse response,String key,String value,int lifeTime){
        //创建cookie
        Cookie cookie = new Cookie(key,value);
        //设置有效期
        //-1：代表内存级别（浏览器窗口关闭，数据删除）
        //0：删除当前数据。设置数据里只是小，删除指定的key的cookie
        //>0：设置浏览器端cookie的保存市场，单位是秒
        cookie.setMaxAge(lifeTime);
        //设置cookie的保存路径,获取当前项目的上下文路径。/day41
        cookie.setPath(request.getContextPath());
        //设置http协议制度
        cookie.setHttpOnly(true);
        //返回前端
        response.addCookie(cookie);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
